package com.unitd.frame.springweb.listener;

import com.unitd.frame.spring.SpringInstanceFactory;
import com.unitd.frame.spring.SpringInstanceProvider;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import java.util.Map;

/**
 * @desc 重写spring的ContextLoaderListener类
 * @filename BaseController.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2016/10/14
 */
public class ContextLoaderListener extends org.springframework.web.context.ContextLoaderListener {

	/**
	 * @desc 重写Spring框架的contextInitialized方法, 主要用于处理当前应用和跨域访问
	 * @param event servlet事件
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		String serviceName = event.getServletContext().getInitParameter("appName");
		System.setProperty("serviceName", serviceName == null ? "undefined" : serviceName);

		String crosAllowOrigin = event.getServletContext().getInitParameter("crosAllowOrigin");
		System.setProperty("crosAllowOrigin", crosAllowOrigin == null ? "*" : crosAllowOrigin);
		super.contextInitialized(event);

		WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(event.getServletContext());
		SpringInstanceProvider provider = new SpringInstanceProvider(applicationContext);
		SpringInstanceFactory.setSpringInstanceProvider(provider);

		Map<String, IContextIinitializedListener> interfaces = applicationContext.getBeansOfType(IContextIinitializedListener.class);
		if (interfaces != null) {
			for (IContextIinitializedListener listener : interfaces.values()) {
				System.out.println(">>>begin to execute listener:" + listener.getClass().getName());
				listener.onContextIinitialized(applicationContext);
				System.out.println("<<<<finish execute listener:" + listener.getClass().getName());
			}
		}
	}
}